<template>
  <div>
    <div class="card-box">
      <el-card class="elcard" style="margin-right:10px;">
        <div slot="header" class="clearfix">
          <span class="tit">科研趋势</span>
        </div>
        <div id="chartOne" style="width:100%;height:390px;"></div>
      </el-card>
      <el-card class="elcard" style="margin-left:10px;overflow:initial;">
        <div slot="header" class="clearfix">
          <span class="tit">领域分布</span>
        </div>
        <div id="chartTwo" style="width:100%;height:390px;"></div>
      </el-card>
    </div>
    <el-card :body-style="{'padding':'0'}" class="elcard">
      <ul class="list-box">
        <li v-for="(item, index) in list" :key="index">
          <div class="logo-box">
            <img width="100%" height="100%" v-if="item.srcImg !== ''" :src="item.srcImg" alt="">
            <img width="100%" height="100%" v-else src="../../../../assets/img/default.png" alt="">
          </div>
          <h2 @click="toDetails(item)">{{item.key}}</h2>
          <p class="info">
            <span>专利数量：<i>{{item.doc_count}}</i></span>
            <span>负责人：<i>{{item.oper_name}}</i></span>
            <span>通讯号码：<i>{{item.phone}}</i></span>
            <span>成立时间：<i>{{item.start_date}}</i></span>
          </p>
          <p class="info">
            <span>
              <em>科研星极：</em>
              <el-rate
                v-model="item.star"
                disabled
                disabled-void-icon-class="el-icon-star-off"
                :allow-half="true"
                class="elrate">
              </el-rate>
            </span>
          </p>
        </li>
      </ul>
      <el-col :span="24" style="text-align:center;padding:10px; 0">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="ipi"
          :page-size="ips"
          :total="total">
        </el-pagination>
      </el-col>
    </el-card>
    
  </div>
  
</template>

<script>
import { mapState } from 'vuex'
import resize from '@/utils/resize'
import Colors from '@/utils/chartsColors'
import axios from 'axios'
export default {
  mixins:[resize],
  data() {
    return {
      chartOne: null,
      chartTwo: null,
      chartTwoData: [],
      maxKey:'',
      Index: '',
      listData: [],
      list: [],
      ips: 5,
      total: 0,
      ipi: 1,
    }
  },
  computed:{
    ...mapState(['levelCode','levelName'])
  },
  methods: {
    goDetail(name){
      this.$Bus.$emit("progressBar", name)
    },
    // 科研趋势-专利
    getPatentData() {
      return this.$post(this.$Url.production.cityAnalysis, {
        code: this.levelCode,
        mustsArr: {
          an1_type: [
            "高校",
            "院所"
          ]
        },
        aggs: {
          field: "ad",
          interval: "YEAR",
          format: "yyyy",
          type: "date"
        },
        rangArr: [
          {
            field: "ad",
            start: this.$DateManag().start,
            end: this.$DateManag().end
          }
        ]
      })
    },
    // 科研趋势-机构
    getInstitutionData() {
      return this.$post(this.$Url.production.cityAnalysis, {
        code: this.levelCode,
        mustsArr: {
          an1_type: [
            "高校",
            "院所"
          ]
        },
        aggs: {
          field: "ad",
          interval: "YEAR",
          format: "yyyy",
          type: "date",
          subAggs: {
            field: "an1",
            size: "500",
            type: "base"
          }
        },
        rangArr: [
          {
            field: "ad",
            start: this.$DateManag().start,
            end: this.$DateManag().end
          }
        ]
      })
    },
    getChartOneData() {
      this.chartOne.showLoading({
        text: 'loading',
        color: '#0b0a2b',
        textColor: '#0b0a2b',
        maskColor: '#fff',
        zlevel: 0
      })
      axios.all([this.getPatentData(), this.getInstitutionData()]).then(axios.spread((res1, res2) => {
        let data1 = res1.data || []
        let data2 = res2.data || []
        let xAxisData = []
        let yAxisData1 = []
        let yAxisData2 = []
        for (let i in data1) {
          xAxisData.push(data1[i].key_as_string)
          yAxisData1.push(data1[i].doc_count)
        }
        for (let i in data2) {
          xAxisData.push(data2[i].key_as_string)
          yAxisData2.push(data2[i].child.length)
        }
        let endYear = String(this.$DateManag().end).split('-')[0]
        xAxisData = Array.from(new Set(xAxisData))
        if (xAxisData[xAxisData.length - 1] !== endYear) {
          xAxisData.push(endYear)
          yAxisData1.push(0)
          yAxisData2.push(0)
        }
        let d = (name, index, data) => {
          let solid = [...data.slice(0, data.length - 1), '-']
          let dotted = []
          for (let i in data) {
            if (i < data.length - 2) {
              dotted.push('-')
            } else {
              dotted.push(data[data.length - 2])
            }
          }
          return [{ // 实线
            type: 'line',
            name: name,
            color: Colors.color[index],
            smooth: 1,
            data: solid,
            areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[index] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[index] + ",0.01)" // 100% 处的颜色
                  }],
                  global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            }
          }, { // 虚线
            type: 'line',
            name: name,
            color: Colors.color[index],
            smooth: 1,
            data: dotted,
            lineStyle: {
              type: 'dotted'
            },
            areaStyle: {
              normal: {
                type: 'radial',
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                      offset: 0, color: "rgba(" + Colors.rgb[index] + ",0.3)" // 0% 处的颜色
                  }, {
                      offset: 1, color: "rgba(" + Colors.rgb[index] + ",0.01)" // 100% 处的颜色
                  }],
                  global: false // 缺省为 false
                },
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowBlur: 10
              }
            }
          }]
        }

        let seriesData = [...d('专利', 0, yAxisData1), ...d('机构', 1, yAxisData2)]
        this.renderChartOne(xAxisData, seriesData)
      })).catch(err => {})
    },
    renderChartOne(xAxisData, seriesData) {
      let option = {
        tooltip: {
          confine: true,
          trigger: "axis",
          backgroundColor: "#fff",
          extraCssText: "box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);",
          borderRadius: 0,
          padding: 5,
          textStyle: {
              color: "#000"
          },
          axisPointer: { type: "none" },
          formatter: function (params, ticket, callback) {
            var htmlStr = '';
            var valMap = {};

            htmlStr += (params[0].name ||  params[3].name)+ '<br/>';//x轴的名称
            
            for(var i=0;i<params.length;i++){
              var param = params[i];
              var xName = param.name;//x轴的名称
              var seriesName = param.seriesName;//图例名称
              var value = param.value;//y轴值
              var color = param.color;//图例颜色
              //过滤无效值
              if(value == '-'){
                continue;
              }
              //过滤重叠值
              if(valMap[seriesName] == value){
                continue;
              }
              htmlStr +='<div>';
              //为了保证和原来的效果一样，这里自己实现了一个点的效果
              htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:'+color+';"></span>';
              //圆点后面显示的文本
              htmlStr += seriesName + '：' + value;
              htmlStr += '</div>';
              valMap[seriesName] = value;
            }
            return htmlStr;
          }
        },
        legend: {
          type: "scroll",
          top: '0'
        },
        grid: {
          top: '50'
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: xAxisData,
          splitLine: {
          show: false,
            lineStyle: {
              color: "#f0f1f3"
            }
          },
          axisLine: {
            lineStyle: {
              color: "#f0f1f3",
              width: 2
            }
          },
          axisLabel: {
            textStyle: {
              color: "#9e9e9e"
            }
          }
        },
        yAxis: {
          type: "value",
          splitLine: {
            show: true,
            lineStyle: {
                color: "#f0f1f3"
            }
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
                color: "#f0f1f3",
                width: 2
            }
          },
          axisLabel: {
            textStyle: {
                color: "#9e9e9e"
            }
          }
        },
        dataZoom: [
          {
            id: 'dataZoomX',
            type: 'inside',
            xAxisIndex: [0],
            filterMode: 'filter'
          }
        ],
        series: seriesData
      }
      this.chartOne.hideLoading()
      this.chartOne.setOption(option, true)
    },
    getChartTwoData() {
      this.chartTwo.showLoading({
        text: 'loading',
        color: '#0b0a2b',
        textColor: '#0b0a2b',
        maskColor: '#fff',
        zlevel: 0
      })
      this.$post(this.$Url.patent.labelAnalysis, {
        code: this.levelCode,
        "level": 3,
        'mustsArr': {
          'an1_type': ["高校","院所"]
        },
        "aggs": {
          "field": "industry_label",
          "type": "base",
          "size": "10000",
          "showSize":10
        }
      }).then(res => {
        let data = res.data
        if (data) {
          let chartData = []
          let d = JSON.parse(JSON.stringify(data))
          d.sort(function (a, b) {
            return Number(a.doc_count)< Number(b.doc_count) ? 1 : -1;
          })
          this.chartTwoData = d // 保存的一个结果
          this.maxKey = d[0].key // 最大key
          let num = d[0].doc_count // 最大值
          
          this.renderChartTwo(d)
        }
      }).catch(err => {})
    },
    renderChartTwo(data, isClick) {
      let seriesData = []
      for(let i in data){
        let NameColor = '#878696'
        let lineColor = '#ccc'
        let fontWeight = '500'
        if(isClick && data[i].key === this.maxKey){
          NameColor='#514bad'
          fontWeight = 'bold'
          lineColor = '#514bad'
        }
        seriesData.push({
          name:data[i].value,
          value: data[i].doc_count,
          key: data[i].key,
          label:{
            normal:{
              rich: {
                name:{
                  color: NameColor,
                  fontWeight: fontWeight 
                } 
              }
            }
          },
          labelLine: {
            normal: {
              lineStyle: {
                color: lineColor
              }
            }
          }
        })
      }
      let option = {
        backgroundColor: '#fff',
        tooltip: {
          trigger: 'item',
          formatter: "{b}: {c} ({d}%)",
          position: 'top'
        },
        grid:{
          top:'50%',
          x: '5%'
        },
        color: Colors.color,
        series: [
          {
            type: 'pie',
            avoidLabelOverlap: true,
            radius: ['34%', '50%'],
            minAngle: 24,
            startAngle: 70, //起始角度
            data: seriesData,
            itemStyle:{
              normal: {
                borderWidth: 2, 
                borderColor: '#fff',
              }
            },
            label: {
              show: true,
              position: 'outer',
              alignTo: 'labelLine',
              distanceToLabelLine: 5,
              formatter: (params) => {
                let str = ''
                if (params.name.length > 10) {
                  str += `{name|${params.name.substring(0, 10)}...}`
                } else {
                  str += `{name|${params.name}}`
                }
                str += `  {name|${params.percent}%}`
                return str
              },
              rich: {
                icon: {},
                name: {
                  fontSize: 12,
                  color: '#86899e'
                },
              }
            },
          }
        ]
      }
      this.chartTwo.hideLoading()
      this.chartTwo.setOption(option, true)
    },
    chartTwoClick(v) {
      this.ipi = 1
      let num = v.data.value
      // 取消之前的高亮 或者默认
      this.chartTwo.dispatchAction({  
        type: 'downplay'
      })
      if (this.Index !== v.dataIndex) {
        this.Index = v.dataIndex // 点击高亮
        this.maxKey = v.data.key
        this.chartTwo.dispatchAction({
          type: "highlight",
          dataIndex: this.Index
        })
        this.getTableData(v.data.key)
      } else {
        this.Index = -1
        this.maxKey = -1
        this.getTableData()
      }
      
      this.renderChartTwo(this.chartTwoData, true)
      
    },
    getTableData(ipc_kind = '') {
      let params ={}
      if(ipc_kind){
        params = {
          code: this.levelCode,
          mustsArr: {
            an1_type: [
              "高校",
              "院所"
            ]
          },
          "prefix":{
            "labels.label":ipc_kind
          },
          aggs: {
            field: "an1",
            size: "100",
            type: "base"
          }
        }
      }else{
        params = {
          code: this.levelCode,
          mustsArr: {
            an1_type: [
              "高校",
              "院所"
            ]
          },
          aggs: {
            field: "an1",
            size: "100",
            type: "base"
          }
        }
      }
      
      /* if (ipc_kind !== '') {
        params['mustsArr']['ipc_kind'] = [ipc_kind]
      } */
      this.$post(this.$Url.production.cityAnalysis, params).then(res => {
        let data = res.data
        if (data) {
          this.listData = data
          this.total = data.length
          let d = JSON.parse(JSON.stringify(this.listData.slice((this.ipi-1)*this.ips,this.ipi*this.ips)))
          this.getListData(d)
        }
      }).catch(err => {})
    },
    getListData(d) {
      this.list = []
      for (let i in d) {
        let obj = d[i]
        obj = {
          srcImg: '',
          oper_name: '',
          start_date: '',
          phone: '',
          ...obj
        }
        this.list.push(obj)
      }
      
      for (let i in d) {
        this.getImg(d[i].key, (imgData, eid) => {
          this.$set(this.list[i], 'srcImg', imgData)
          this.$set(this.list[i], 'eid', eid)
        })
        this.getDetailInfo(d[i].key, (info) => {
          this.$set(this.list[i], 'oper_name', info.result[0] && info.result[0]._source && info.result[0]._source.oper_name)
          this.$set(this.list[i], 'start_date', (info.result[0] && info.result[0]._source && info.result[0]._source.start_date) || '暂无')
        })
        this.getCompanyScore(d[i], (star) => {
          this.$set(this.list[i], 'star', star)
        })
      }
    },
    // 获取公司详情
    getDetailInfo(name, func) {
      this.$post(this.$Url.search.companyList, {
        name: name,
        ipi: 1,
        ips: 1
      }).then(res => {
        let data = res.data
        if (data) {
          func(data)
        }
      }).catch(err => {})
    },
    getImg(companyName, func) {
      let promise = new Promise((resolve, reject) => {
        this.$post(this.$Url.search.companyList, {
          name: companyName,
          ipi: 1,
          ips: 1
        }).then(res => {
          let data = res.data
          if (data) {
            let eid = data.result && data.result[0]._id
            resolve(eid)
          }
        }).catch(err => {})
      })
      promise.then((eid) => {
        this.$get(this.$Url.search.companyLogo, {
          eid: eid
        }).then(res => {
          let data = res.data
          return func(data, eid)
        }).catch(err => {})
      })
    },
    // 科研星级
    getCompanyScore(d, func) {
      let doc_count = d.doc_count
      let newCount = 0
      let star = 0
      if (doc_count > 5000) {
        newCount = 100
      } else if (doc_count > 1000) {
        newCount = 80
      } else if (doc_count > 500) {
        newCount = 70
      } else if (doc_count > 300) {
        newCount = 60
      } else if (doc_count > 200) {
        newCount = 50
      } else if (doc_count > 100) {
        newCount = 40
      } else if (doc_count > 50) {
        newCount = 30
      } else {
        newCount = 20
      }
      star = newCount / 100 * 5
      func && func(star)
    },
    // 分页
    handleCurrentChange(val){
      this.ipi = val
      this.list = this.listData.slice((this.ipi-1)*this.ips,this.ipi*this.ips)
      this.getListData(this.list)
    },
    headerCellStyle() {
      return {
        'font-weight': 'normal',
        'color': '#86899e',
        'background-color': '#f3f6f9'
      }
    },
    // 跳转到机构详情
    toDetails(item) {
      this.$router.push({
        name: 'SynergyInsDetails',
        query: {
          name: item.key,
          eid: item.eid,
          doc_count: item.doc_count
        }
      })
    }
  },
  mounted() {
    this.chartOne = this.$echarts.init(document.getElementById('chartOne'))
    this.chartTwo = this.$echarts.init(document.getElementById('chartTwo'))
    this.chartTwo.on('click', this.chartTwoClick)
    this.getChartOneData()
    this.getChartTwoData()
    this.getTableData()
  }
}
</script>

<style lang="scss" scoped>
.card-box {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.elcard {
  flex: .5;
  text-align: left !important;
  .tit {
    font-size: 14px;
    font-weight: bold;
  }
}
.list-box {
  position: relative;
  list-style: none;
  li {
    position: relative;
    display: block;
    min-height: 140px;
    padding-top: 20px;
    padding-bottom: 20px;
    padding-left: 140px;
    border-bottom: 1px solid #e5e7f0;
    .logo-box {
      position: absolute;
      top: 20px;
      left: 20px;
      width: 100px;
      height: 100px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #d9e0ee;
      box-sizing: border-box;
    }
    h2 {
      width: 100%;
      // margin-top: 10px;
      // margin-top: 10px;
      margin-bottom: 20px;
      font-size: 18px;
      font-weight: bold;
      color: #4f515b;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      cursor: pointer;
    }
    .info {
      display: flex;
      align-items: center;
      width: 80%;
      margin-top: 10px;
      // margin-top: 30px;
      span {
        flex: 1;
        font-size: 12px;
        color: #86899e;
        i {
          font-style: normal;
          color: #4f515b;
        }
        em {
          vertical-align: middle;
        }
      }
      .elrate {
        display: inline-block;
        vertical-align: unset;
      }
    }
  }
}

</style>